var form, table, layer, jquery, node, index, dicVal, canView, canEdit, calDefault, pluginType, data;

var ATTR_OPINION = 'opinion';
var ATTR_IS_NULL = 'if-required';
var ATTR_CAN_VIEW = 'can-view';
var ATTR_CAN_EDIT = 'can-edit';
var ATTR_DIC_VALUE = 'dic-value';
var ATTR_NAME = 'name';
var ATTR_CN_NAME = 'cn-name';
var ATTR_WEI_TYPE = 'ext-type';
var ATTR_DEFAULT_VALUE = 'default-value';
var ATTR_DEFAULT_SHOW = 'default-show';
var ATTR_EVENT = 'bind-event';
var ATTR_CLICK = 'click-event';
var ATTR_IS_PAGE = 'page';
var PAGE_SIZE = 'pagesize';
var LIMITS = 'limits';
var COLS = 'cols';
var DICT_ATTR = 'dict-attr';
var cols=[];
var formId = RequestURLParam.getParam('formId') || "";
var moduleId = RequestURLParam.getParam('moduleId') || "";

var lnHtml;
var index = 0;
var number = 0;

$('body').after($.ajax({url: mPath + 'data/opdiv.ml', async: false}).responseText) || "";

/**
 * 加载lalyui模块
 */
layui.use(['form', 'table', 'layer', 'jquery','element'], function () {
    form = layui.form;
    table = layui.table;
    laydate = layui.laydate;
    jquery = layui.jquery;
    element = layui.element;

});

$(function () {
    var lnAttrs = ['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allowfullscreen', 'allowtransparency', 'alt', 'async', 'autocomplete', 'autofocus', 'autoplay', 'autosave', 'background', 'bgcolor', 'border', 'charset', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'color', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'data', 'data-.*', 'datetime', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'dropzone', 'enctype', 'for', 'form', 'formaction', 'frameborder', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'mozallowfullscreen', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'scrolling', 'seamless', 'selected', 'shape', 'size', 'sizes', 'span', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'spellcheck', 'style', 'tabindex', 'target', 'title', 'type', 'translate', 'usemap', 'value', 'valign', 'webkitallowfullscreen', 'width', 'wrap', 'plugin-id', 'plugin-name', 'plugin-type', 'is-null', 'cal-default', 'can-view', 'can-edit', 'dic-value', 'cn-name', 'ext-type', 'default-value', 'isnull', 'calDefault', 'if-required', 'bind-event', 'click-event', 'default-show', 'page', 'pagesize', 'limits', 'cols', 'opinion', 'obj-type','dict-attr','lay-verify'];
    var lnTags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'queue', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'style', 'section', 'select', 'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr'];
    $('#edit').froalaEditor({
        language: 'zh_cn',
        htmlAllowedAttrs:lnAttrs,
        htmlRemoveTags: ['base'],
        htmlAllowComments: true
    });
    initData();
    initEvent();
});

function initData() {
    lnHtml = JSON.parse($.ajax({
        data: {'id': formId},
        url: '/wf/form/findById',
        type:'post',
        async: false
    }).responseText);

    $('#edit').froalaEditor('html.set', lnHtml.wfForm.formHtml);

    $('#ln-attr').html($.ajax({url: mPath + 'data/attr.ml', async: false}).responseText);
    $('#ln-tab').html($.ajax({url: mPath + 'data/tab.ml', async: false}).responseText);

    var pluginInfo = JSON.parse($.ajax({
        data: {'moduleId': moduleId, 'pluginsState':'1'},
        url: '/wf/form/plugins/list',
        type:'post',
        async: false
    }).responseText);

    Array.from(pluginInfo['List']).forEach(function (v) {
        var tHtml = '<li><button name="{0}" content=\'{1}\' onclick="inPlugin($(this).attr(\'content\'))">{2}</button></li>'.format(v.name, v.htmlContent, v.nameCn);
        $("#models").find("li").last().after(tHtml);
    });

    var TyValue = JSON.parse($.ajax({
        url: '/sys-code/list',
        data: {
            "codeTypeName": "liuchengbiaodangonggongkongjianleixing",
            "codeIsParent": "2"
        },
        type:'post',
        async: false
    }).responseText);

    Array.from(TyValue['List']).forEach(function (v) {
        if(v.codeName != "意见控件" && v.codeName != "意见控件2" && v.codeShow != "todouser" && v.codeShow != "img" ){
            var content = "<input name="+"m-"+v.codeShow+" type='text' ext-type="+ v.codeShow +" cn-name="+ v.codeName +"/>"
            var tHtml = '<li><button name="'+ v.codeShow +'" content="'+ content + '" onclick="inPlugin($(this).attr(\'content\'))">'+v.codeName+'</button></li>';
            $("#common").find("li").last().after(tHtml);
        }else if(v.codeShow == "todouser"){
            var content = "<input name="+"m-"+v.codeShow+" type='text' ext-type="+ v.codeShow +" cn-name="+ v.codeName +" click-event="+2+" />"
            var tHtml = '<li><button name="'+ v.codeShow +'" content="'+ content + '" onclick="inPlugin($(this).attr(\'content\'))">'+v.codeName+'</button></li>';
            $("#common").find("li").last().after(tHtml);
        }
    });

}

function initEvent() {
    $("#ln-tab div").bind("click", this, function (e) {
        $("#ln-tab div").removeClass("show_ul");
        $(this).addClass("show_ul");
    });
    $(".prInfo input").bind("blur", this, function (e) {
        var el = $(e.currentTarget);
        saveWidget(el);
    });
    $(".prInfo>h5").bind("click", this, function (e) {
        var el = $(e.currentTarget);
        el.next().slideToggle("fast");
    });
    reEvent();
    $('.selector').on('froalaEditor.commands.after', function (e, editor, cmd, param1, param2) {
        reEvent();
        if(cmd == "html"){
            index ++;
            node = $('input.ln-sel-input');
            if(index%2 != 0){
                $('#ln-attrDiv').hide();
            }else{
                $('#ln-attrDiv').show();
            }
        }

    });
}

function reEvent() {
    //重复事件
    $("#edit").find("input").unbind("focus").bind("focus", function (e) {
        node = $(e.currentTarget);
        node.addClass('ln-sel-input').parents('div.selector').find('input').not(node).removeClass('ln-sel-input');
        initElEvent();
    });
}

function initElEvent() {
    if(node.attr(ATTR_WEI_TYPE) == "datagrid"){
        $('#ln-attr').html($.ajax({url: mPath + 'data/tableAttr.ml', async: false}).responseText);
        $('#pluginName').val(node.attr(ATTR_NAME));
        $('#pluginCnName').val(node.attr(ATTR_CN_NAME));
        // $('#isPage').prop('checked', (node.attr(ATTR_IS_PAGE) == "true") ? true : false);
        // if((node.attr(ATTR_IS_PAGE) == "true") ? true : false){
        //     $('#pageConfigDiv').show();
        // }else{
        //     $('#pageConfigDiv').hide();
        // }
        // $('#pageSize').val(node.attr(PAGE_SIZE));
        // $('#limits').val(node.attr(LIMITS));

    }else{
        $('#ln-attr').html($.ajax({url: mPath + 'data/attr.ml', async: false}).responseText);
        $('#pluginName').val(node.attr(ATTR_NAME));
        $('#pluginCnName').val(node.attr(ATTR_CN_NAME));
        $('#isNull').prop('checked', (node.attr(ATTR_IS_NULL) == "true") ? true : false);

        selType();
        selDefault();
        selEvent();
        selClickEvent();
    }
    $('.prInfo').css("display", "block");
}

//默认值选择
function selDefault() {
    node = $('input.ln-sel-input');
    var DfValue = JSON.parse($.ajax({
        url: '/sys-code/list',
        data: {
            "codeTypeName": "liuchengbiaodanmorenzhi",
            "codeIsParent": "2"
        },
        type:'post',
        async: false
    }).responseText);
    var nodeDefault=node.attr(ATTR_DEFAULT_VALUE);
    var tHtml="<br>";
    Array.from(DfValue['List']).forEach(function (v) {
        var mtl = '<span name="{0}">{1}</span>'.format(v.codeValue,v.codeName);
        if ("undefined"!=typeof nodeDefault&&nodeDefault==v.codeValue)
            mtl = '<span name="{0}" class="prop_edit_btn_sel">{1}</span>'.format(v.codeValue,v.codeName);
        tHtml+=mtl;
    });
    $("#prop_edit_default").html(tHtml);
    $("#prop_edit_default").find("span").bind("click",function (eve) {
        node = $('input.ln-sel-input');
        var el = $(eve.currentTarget);
        if(el.hasClass("prop_edit_btn_sel")){
            el.removeClass("prop_edit_btn_sel");
            node.attr(ATTR_DEFAULT_VALUE,"");
        }else {
            el.addClass("prop_edit_btn_sel").siblings().removeClass("prop_edit_btn_sel");
            node.attr(ATTR_DEFAULT_VALUE,el.attr("name"));
        }
    });
}

//数据绑定
function selEvent() {
    node = $('input.ln-sel-input');
    var DfValue = JSON.parse($.ajax({
        url: '/sys-code/list',
        data: {
            "codeTypeName": "liuchengbiaodanbangdingshuju",
            "codeIsParent": "2"
        },
        type:'post',
        async: false
    }).responseText);
    var nodeDefault=node.attr(ATTR_EVENT);
    var tHtml="<br>";
    Array.from(DfValue['List']).forEach(function (v) {
        var mtl = '';
        if ("undefined"!=typeof nodeDefault&&nodeDefault==v.codeValue){
            mtl = '<span name="{0}" class="prop_edit_btn_sel">{1}</span>'.format(v.codeValue,v.codeName);
        }else {
            mtl = '<span name="{0}">{1}</span>'.format(v.codeValue, v.codeName);
        }
        tHtml+=mtl;
    });
    $("#prop_edit_event").html(tHtml);
    $("#prop_edit_event").find("span").bind("click",function (eve) {
        node = $('input.ln-sel-input');
        var el = $(eve.currentTarget);

        if(el.hasClass("prop_edit_btn_sel")){
            el.removeClass("prop_edit_btn_sel");
            node.attr(ATTR_EVENT,"");
        }else {
            el.addClass("prop_edit_btn_sel").siblings().removeClass("prop_edit_btn_sel");
            node.attr(ATTR_EVENT,el.attr("name"));
        }
    });
}

//控件点击事件绑定
function selClickEvent() {
    node = $('input.ln-sel-input');
    var DfValue = JSON.parse($.ajax({
        url: '/sys-code/list',
        data: {
            "codeTypeName": "liuchengbiaodankongjiandianjishijian",
            "codeIsParent": "2"
        },
        type:'post',
        async: false
    }).responseText);
    var nodeDefault=node.attr(ATTR_CLICK);
    var tHtml="<br>";
    Array.from(DfValue['List']).forEach(function (v) {
        var mtl = '<span name="{0}">{1}</span>'.format(v.codeValue,v.codeName);
        if ("undefined"!=typeof nodeDefault&&nodeDefault==v.codeValue)
            mtl = '<span name="{0}" class="prop_edit_btn_sel">{1}</span>'.format(v.codeValue,v.codeName);
        tHtml+=mtl;
    });
    $("#prop_edit_click").html(tHtml);
    $("#prop_edit_click").find("span").bind("click",function (eve) {
        node = $('input.ln-sel-input');
        var el = $(eve.currentTarget);

        if(el.hasClass("prop_edit_btn_sel")){
            el.removeClass("prop_edit_btn_sel");
            node.attr(ATTR_CLICK,"");
        }else {
            el.addClass("prop_edit_btn_sel").siblings().removeClass("prop_edit_btn_sel");
            node.attr(ATTR_CLICK,el.attr("name"));
        }
    });
}

//控件类型选择
function selType() {
    node = $('input.ln-sel-input');
    var TyValue = JSON.parse($.ajax({
        url: '/sys-code/list',
        data: {
            "codeTypeName": "liuchengbiaodangonggongkongjianleixing",
            "codeIsParent": "2"
        },
        type:'post',
        async: false
    }).responseText);
    var nodeDefault=node.attr(ATTR_WEI_TYPE);
    var tHtml="<br>";
    Array.from(TyValue['List']).forEach(function (v) {
        if(v.codeName != "意见控件" && v.codeName != "下一环节指定办理人" && v.codeName != "图片上传"){
            var mtl = '<span name="{0}">{1}</span>'.format(v.codeShow,v.codeName);
            if ("undefined"!=typeof nodeDefault&&nodeDefault==v.codeShow)
                mtl = '<span name="{0}" class="prop_edit_btn_sel">{1}</span>'.format(v.codeShow,v.codeName);
            tHtml+=mtl;
        }else{

        }

    });
    $("#prop_edit_type").html(tHtml);
    $("#prop_edit_type").find("span").bind("click",function (eve) {
        node = $('input.ln-sel-input');
        var el = $(eve.currentTarget);
        el.addClass("prop_edit_btn_sel").siblings().removeClass("prop_edit_btn_sel");
        node.attr(ATTR_WEI_TYPE,el.attr("name"));
    });
}

/**
 * 向富文本插入代码
 * @param ml
 */
function inPlugin(ml) {
    // number += 1;
    $('.selector').find('input.ln-sel-input').removeClass('ln-sel-input');
    var name = $(ml).attr('name');
    var type = $(ml).prop('ext-type');
    var length = $('.selector').find('input[ext-type*='+ type +']').length;

    if(type == "todouser" && length > 0){
        layer.msg("该控件已存在", {icon:2});
        return false;
    }

    if($(ml).prop("tagName") == "TABLE"){
        var length1 = $('.selector').find('table[name*='+ name +']').length;
        if(length1 > 0){
            name = name + length1;

            $(ml).find('input').each(function () {
                var oldName = $(this).attr("name");
                var opinion = $(this).attr("opinion");
                var html = $(this).prop("outerHTML");
                var newName = oldName+length1;
                var newhtml = html.replace(oldName, newName);
                newhtml = newhtml.replace(opinion, opinion+length1);
                ml = ml.replace(html, newhtml);
            });
        }
        $('#edit').froalaEditor('html.insert', $(ml).attr('name', name).prop('outerHTML'), true);

    }else if($(ml).prop("tagName") == "DIV"){
        var length1 = $('.selector').find('div[name*='+ name +']').length;
        if(length1 > 0){
            name = name + length1;

            $(ml).find('input').each(function () {
                var oldName = $(this).attr("name");
                var html = $(this).prop("outerHTML");
                var newName = oldName+length1;
                var newhtml = html.replace(oldName, newName);
                ml = ml.replace(html, newhtml);
            });
        }
        $('#edit').froalaEditor('html.insert', $(ml).attr('name', name).prop('outerHTML'), true);
    }else{
        var length1 = $('.selector').find('input[name*='+ name +']').length;
        if(name == "m-text" ){
            var l1 = $('.selector').find('input[name*="m-textarea"]').length;
            length1 = length1-l1;
        }else if( name == "m-date"){
            var l1 = $('.selector').find('input[name*="m-datetime"]').length;
            length1 = length1-l1;
        }
        if(length1 > 0){
            name = name + length1;
        }
        $('#edit').froalaEditor('html.insert', $(ml).addClass('ln-sel-input').attr('name', name).prop('outerHTML'), true);
    }

    reEvent();
    $('.selector').find('input.ln-sel-input').trigger("focus");
}

/**
 * 保存控件值
 * @param el
 */
function saveWidget(el) {
    node = $('input.ln-sel-input');
    Array.from($('.prInfo [lnAttr]')).forEach(function (v) {
        node.attr($(v).attr('lnAttr'), $(v).val());
    });
    node.attr('if-required', $("#isNull").prop('checked'));
}

/**
 * 删除控件
 */
function deleteWidget() {
    node.remove();
    $('.prInfo').css("display", "none");
}

/**
 * 保存表单
 */
function saveForm() {

    node = $('input.ln-sel-input');
    Array.from($('.prInfo [lnAttr]')).forEach(function (v) {
        node.attr($(v).attr('lnAttr'), $(v).val());
    });
    if(node.attr(ATTR_WEI_TYPE) == "datagrid"){
        // node.attr(PAGE_SIZE ,$("#pageSize").val());
        // node.attr(LIMITS, $("#limits").val());
    }

    $('.prInfo').css("display", "none");

    $('.selector input.ln-sel-input').removeClass('ln-sel-input');

    lnHtml = $('#edit').froalaEditor('html.get', true);

    lnHtml = lnHtml.replace(/\'/g,"\"").replace("\"Times New Roman\"", "Times New Roman");

    var flag = $.ajax({
        type: 'POST',
        data: {'formId': formId, 'formHtml': lnHtml},
        url: '/wf/form/update',
        type:'post',
        async: false
    }).responseText;

    if(flag){
        layer.msg("表单保存成功！")
    }else {
        layer.msg("表单保存失败！")
    }
}

//字典管理
function dectionary() {
    node = $('input.ln-sel-input');
    var frameId = window.frameElement && window.frameElement.id || '';
    var dicValue = node.attr(ATTR_DIC_VALUE);
    parent.layer.open({
        type: 2
        ,title: '添加字典'
        ,area: ['850px', '700px']
        ,maxmin: false
        ,content: '../../workFlow/froala/wfDictionaryList.html?dicValue='+ dicValue +'&iframeId='+frameId
        ,zIndex: layer.zIndex
    });

}

//权限配置
function privilege() {
    node = $('input.ln-sel-input');
    var frameId = window.frameElement && window.frameElement.id || '';

    var viewId = node.attr('can-view');
    var editId = node.attr('can-edit');

    ActHttpRequest("/wf/workflow/getByFormId",{"fid" : formId},function (data) {
        if(data.List == null || data.List.length == 0){
            layer.msg("表单还没绑定流程！",{ icon:2,time:1200 });
        }else{
            var wfId = data.List[0].wfId;
            parent.layer.open({
                type: 2
                ,title: '权限配置'
                ,area: ['850px', '700px']
                ,maxmin: false
                ,content: '../../workFlow/froala/privilege.html?formId='+ formId +'&viewId='+ viewId +'&editId='+ editId +'&wfId='+ wfId +'&iframeId='+frameId
                ,zIndex: layer.zIndex
            });
        }
    });
}

//默认值权限配置
function defValPrivilege() {
    node = $('input.ln-sel-input');
    var frameId = window.frameElement && window.frameElement.id || '';

    var viewId = node.attr('default-show');
    var defaultValue = node.attr('default-value');

    if(defaultValue == null || defaultValue == undefined || defaultValue == ""){
        layer.msg("当前控件没有绑定默认值！",{ icon:2,time:1200 });
    }else{
        ActHttpRequest("/wf/workflow/getByFormId",{"fid" : formId},function (data) {
            if(data.List == null || data.List.length == 0){
                layer.msg("表单还没绑定流程！",{ icon:2,time:1200 });
            }else{
                var wfId = data.List[0].wfId;
                parent.layer.open({
                    type: 2
                    ,title: '默认值配置'
                    ,area: ['850px', '700px']
                    ,maxmin: false
                    ,content: '../../workFlow/froala/defValPrivilege.html?formId='+ formId +'&viewId='+ viewId +'&wfId='+ wfId +'&iframeId='+frameId
                    ,zIndex: layer.zIndex
                });
            }
        });
    }

}

//表头配置
function tableConfig() {
    node = $('input.ln-sel-input');
    var frameId = window.frameElement && window.frameElement.id || '';
    cols = node.attr('cols');
    parent.layer.open({
        type: 2
        ,title: '表头配置'
        ,area: ['850px', '700px']
        ,maxmin: false
        ,content: '../../workFlow/froala/tableConfig.html?formId='+ formId +'&iframeId='+frameId
        ,zIndex: layer.zIndex
    });
}

//配置分页
// function savePage() {
//     node = $('input.ln-sel-input');
//     Array.from($('.prInfo [lnAttr]')).forEach(function (v) {
//         node.attr($(v).attr('lnAttr'), $(v).val());
//     });
//     node.attr('page', $("#isPage").prop('checked'));
//     if($("#isPage").prop('checked')){
//         $("#pageConfigDiv").show();
//     }else {
//         $("#pageConfigDiv").hide();
//     }
// }
